var express = require('express');
var router = express.Router();
const  query  = require('../conn/conn');
const  sendMail  = require('../public/javascripts/sendMail');
const  path = require('path');
const  fs  = require('fs');
const  jwt  =  require('jsonwebtoken');

/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });
router.get('/getcode', async(req, res, next) => {
    let email = req.query.username;
    let result = await query(`select * from user where username='${email}'`)
    if (result.length) {
        res.send({ mas: "账号已存在", success: 0 })
    } else {
        let code = sendMail(email);
        fs.writeFile(path.join(__dirname, '..', 'temp', email), code, 'utf8', err => {
            if (err) console.log(err);
            res.send({ msg: '邮件已发送', success: 1 });
        });
    }
});

router.post('/register', (req, res, next) => {
    let email = req.body.params.username;
    let code = req.body.params.code;
    let psw = req.body.params.password;
    console.log(email, code, psw)

    fs.readFile(path.join(__dirname, '..', 'temp', email), 'utf8', async(err, data) => {
        if (err) {
            console.log(err)
            res.send({ msg: '邮箱错误', success: 0 })
        } else if (code == data) {
            res.send({ msg: '注册成功', success: 1 });
            await query(`insert into user (username,password) values ('${email}','${psw}')`);
            fs.unlink(path.join(__dirname, '..', 'temp', email), err => {
                if (err) console.log(err)
                console.log('文件已删除')
            })
        } else {
            res.send({ mag: '验证码错误', success: 2 })
        }
    })
})


router.get('/login', async(req, res, next) => {
    const { username, password } = req.query
    console.log(req.query)
    console.log(username);
    console.log(password);
    let result = await query(`select * from user where username='${username}' and  password='${password}'`)

    if (result.length) {
        const user = {
            username: username,
            logintime: Date.now(),
        }
        const token = 'Bearer ' + jwt.sign(user, 'xxx', { expiresIn: 60 * 60 * 24 })
        return res.send({
            msg: '登陆成功',
            success: 1,
            token
        })
    }
    return res.send({
        msg: '登陆失败',
        success: 0

    })
});


module.exports = router;